//
//  BookDetailController.m
//  悦读
//
//  Created by dllo on 15/5/22.
//  Copyright (c) 2015年 贾建兴. All rights reserved.
//

#import "BookDetailController.h"
#import "SANetWorkingTask.h"
#import "IntroTableViewCell.h"
#import "IntroduceTableViewCell.h"
#import "BookReadController.h"
#import "CollectClass.h"
#import "WZSnakeHUD.h"
@interface BookDetailController ()<UITableViewDataSource, UITableViewDelegate,IntroTableViewCellDelegate>

@property (nonatomic, retain) UITableView *detailTable;
@property (nonatomic, retain) NSMutableDictionary *detailDic;
@property(nonatomic, retain)NSMutableArray *typeArray;

@end

@implementation BookDetailController


- (void)dealloc
{
    [_detailTable release];
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.detailDic = [NSMutableDictionary dictionary];
        self.typeArray = [NSMutableArray array];
       
    }
    return self;
}

- (void)loadView
{
    [super loadView];

 
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *right = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:self action:@selector(action)];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationItem.rightBarButtonItem = right;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"书籍详情";
    NSDictionary *dic = @{@"version":@"1.3", @"bookid":self.str};
    // 设置页面背景图片
    UIImageView *backImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    backImage.image = [UIImage imageNamed:@"back02.jpg"];
    [self.view addSubview:backImage];
    [backImage release];
    
    __block BookDetailController *bookDetail = self;
    
    //   
    [SANetWorkingTask request:@"http://vip.hentr.com/zhuibook/api/zhuibook/GetBookInfo.do" parmaters:dic block:^(NSDictionary *result) {
        NSDictionary *dic = [result objectForKey:@"response"];
        bookDetail.detailDic = [dic objectForKey:@"ReturnData"];
        if (bookDetail.detailDic.count != 0) {
            [WZSnakeHUD hide];
        }
        [bookDetail.detailTable reloadData];
    }];
    
    
    
    NSDictionary *dic1 = @{@"bookid":self.str};
    [SANetWorkingTask request:@"http://vip.hentr.com/zhuibook/api/zhuibook/getBookCategoryList.do" parmaters:dic1 block:^(NSDictionary *result) {
        
        if ([[[result objectForKey:@"response"] objectForKey:@"ReturnData"] isEqual:[NSNull null]]) {
            
        } else {
            
            [bookDetail.typeArray addObjectsFromArray:[[result objectForKey:@"response"] objectForKey:@"ReturnData"]];
            [bookDetail.detailTable reloadData];
        }
    }];

    [self createDetailTable];
}
- (void)action:(id)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 保存
- (void)action
{
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
//    if ([[self.detailDic valueForKey:@"bookName"] isEqualToString:@"null"])
    if (self.detailDic.count == 0)     {
        NSArray *arr = [CollectClass readArray];
        BOOL judge = [CollectClass judgeData:arr object:self.str];
        if (judge == YES) {
           
            [self showAlert:@"已收藏"];
            
        } else {
        

            [self showAlert:@"数据未加载完, 不能收藏, 请等待"];
        }
        
    } else {
        [dic setObject:[self.detailDic objectForKey:@"bookid"] forKey:@"bookid"];
        [dic setObject:[self.detailDic objectForKey:@"bookName"] forKey:@"bookName"];
        [dic setValue:[self.detailDic valueForKey:@"imageUrl"] forKey:@"imageUrl"];
    
        [CollectClass writeArray:dic];
        
        //???????????
//        NSArray *array = [CollectClass readArray];
       
        
     }
    

}

//弹出框
- (void)timerFireMethod:(NSTimer*)theTimer
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert = NULL;
}
- (void)showAlert:(NSString *) _message
{
    //时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"提示:" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerFireMethod:) userInfo:promptAlert repeats:YES];
    [promptAlert show];
}

#pragma mark 网络请求和数据解析

#pragma mark 创建tableView
- (void)createDetailTable
{
    
    self.detailTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) style:UITableViewStylePlain];
    
    self.detailTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.detailTable.bounces = NO;
    
    self.detailTable.delegate = self;
    self.detailTable.dataSource = self;
    [self.view addSubview:self.detailTable];
    [self.detailTable release];
    
    self.detailTable.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
}



#pragma  mark 执行tableView的协议方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        static NSString *cellIndentify = @"jia";
        IntroTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentify];
        if (!cell) {
            cell = [[IntroTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentify];
        }
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       //给书籍详情的图片,作者等信息赋值
        if (self.detailDic.count != 0) {
            cell.readButton.enabled = YES;
        }
        [cell getDataWithDic:self.detailDic array:self.typeArray];
        return cell;
    }
    
    if (indexPath.row == 1) {
        
        static NSString *cellIndentify = @"jian";
        IntroduceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentify];
        if (!cell) {
            cell = [[IntroduceTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIndentify];
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.introduceLabel.text = [self.detailDic objectForKey:@"intro"];
        if ([cell.introduceLabel.text isEqualToString:@"null"]) {
            cell.introduceLabel.text = @"暂无简介";
        }
        return cell;

        
        
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 160;
    }
    
    if (indexPath.row == 1) {
        //设置小说简介内容的自适应高度
        NSString *str = [self.detailDic objectForKey:@"intro"];
        NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
        CGRect rect = [str boundingRectWithSize:CGSizeMake(350, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return rect.size.height + 10;
    }
    return 100;
}


#pragma mark - cell里的协议实现
//点击阅读本书,进入阅读界面
- (void)toRead
{
    
   NSString *isPlay = [self.detailDic objectForKey:@"isPay"];
        BookReadController *bookRead = [[BookReadController alloc] init];
        bookRead.sourceId= isPlay;
        UINavigationController *readNav = [[UINavigationController alloc] initWithRootViewController:bookRead];
        [self presentViewController:readNav animated:YES completion:nil];
        
        
        [bookRead release];
        [readNav release];
  
    
 
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
